<template>
  <div class="remote-schedule-container">
    <a-spin :spinning="loading">
      <a-form layout="vertical" class="operate-page-form" :model="formState" @validateFields="handleOk" ref="formRef">
        <div class="operate-page-content"> 
          <!-- <img src="../../../../assets/images/ai-bg.png" alt="" class="ai-bg-img"> -->
          <div class="text-center text-white ft-size28 pt-10">{{ $t('other.jackAiScheduling') }}</div>
          <div class="text-center text-white ft-size20 pb-30 pt-5">{{ $t('other.helpYouSolveTheProductionSchedulingProblemWithOneClick') }}</div>
          <MakeDetailTable ref="makeDetailTable" :recordInfo="recordInfo" :personList="personList" :stationList="stationList"/>
          <div class="content-container">
            <section class="make-info-box"> 
              <div class='h-28 mb-13 line-bg pl-14 line-height-28'>{{$t('other.makeMsg')}}</div>
              <div class="chose-container">
                <div>
                  <div class="width-70"> 
                    <div class="mb-10"><span class="text-red">*</span>{{$t('other.processLine')}}</div>
                    <div >
                      <a-form-item name="lineId" :rules="{ required: true, message: $t('other.selectLine')}">
                        <a-select v-model:value="formState.lineId" :placeholder="$t('common.pleaseSelect')" size="large">
                          <template #suffixIcon>
                            <img src="../../../../assets/images/downArrow.png" alt="" style="width:14px;height:12px">
                          </template>
                          <a-select-option v-for="item in lineList" :key="item.key" :value="item.id">
                            <span class="block-red"></span> {{item.name}}
                          </a-select-option>
                        </a-select>
                      </a-form-item>
                    </div>
                  </div>
                </div>
                <div>
                  <div class="width-70" @click="addPerson"> 
                    <div class="mb-10"><span class="text-red">*</span>{{$t('other.pordUser')}}</div>
                    <div class="choose-box">
                      <div> 
                        <span class="block-red"></span>
                        {{$t('common.selected')}} {{personList?.length}} {{$t('other.people')}}
                      </div>
                      <div><plus-outlined /></div>
                    </div>
                  </div>
                </div>
                <div>
                  <div class="width-70" @click="addStation"> 
                    <div class="mb-10"><span class="text-red">*</span>{{$t('other.prodSite')}}</div>
                    <div class="choose-box">
                      <div> 
                        <span class="block-red"></span>
                        {{$t('common.selected')}} {{stationList?.length}} {{$t('other.stand')}}
                      </div>
                      <div><plus-outlined /></div>
                    </div>
                  </div>
                </div>
              </div>
            </section>
            <div class='h-28 mb-13 line-bg pl-14 line-height-28'>{{$t('hangManage.processInfo')}}</div>
            <OperateProcList ref="operateProcList" :moId="recordInfo.moId"  /> 
          </div>
        </div>
        <div class="operate-page-btns">
          <a-space>
            <a-button @click="closeTab" class="cancel">{{$t('common.cancel')}}</a-button>
            <a-button @click="handleOk(1)" type="primary" class="confirm" >{{ $t('other.aiSchedule') }}</a-button>
          </a-space>
        </div>
      </a-form>
    </a-spin>
    <AddStationModal ref="addStationModalRef" @ok="onAddStationOk" />
    <AddPersonModal ref="addPersonModalRef" @ok="onAddPersonOk" />
    <AddRouteModal ref="addRouteModalRef" @ok="otherOperate" />
    <LoadingDiag ref="loadingDiagRef" @ok="okLoading" />
  </div>
</template>
<script setup >
import MakeDetailTable from './makeDetailTables.vue'
import OperateProcList from './operateProcList.vue'
import AddPersonModal from './addPersonModal.vue'
import AddStationModal from './addStationModal.vue'
import AddRouteModal from './addRouteModal.vue'
import LoadingDiag from './loadingDiag.vue' 
import { ref, computed, onMounted  } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import axios from '@/utils/request'
import { cloneDeep ,isEmpty} from 'lodash'
import { store } from '@/store' 
import i18n from '@/locales/index'
const { t } = i18n.global 

const route = useRoute()
const router = useRouter()
let recordInfo = ref({})
let loading = ref(false)
let addStationModalRef = ref()
let addPersonModalRef = ref()
let addRouteModalRef = ref()
let loadingDiagRef = ref()
let personList = ref([])
let stationList = ref([])
let lineList = ref([])
let lineStationList = ref([])

const tabs = computed(() => {
  return store.state.setting.tabs
}) 
let formState = ref({})
const formRef = ref()
const makeDetailTable = ref()
const operateProcList = ref()
const staffList = ref([])
const staffGroupList = ref([])

const addStation = async () => {
  if (!formState.value.lineId){
    message.error(t('deviceManage.pleaseSelectWaterLineNo'))
    return
  }
  const res = await axios.postAction('/api/device/station/get-hangerLineId-by-station', {
    hangerLineIdList: [formState.value.lineId]
  })
  if (res.success && !isEmpty(res.data)){
    addStationModalRef.value.open(res.data,stationList.value)
  }else{
    message.warning(t('other.waterLineDownNotStation'))
  }
}

const addPerson = async () => {
  if (!isEmpty(staffList.value)){
    addPersonModalRef.value.open( staffList.value , staffGroupList.value ,personList.value)
  }else{
    message.warning(t('other.productStaffNotExist'))
  }
}
const onAddStationOk = (fileList) => {
  stationList.value = fileList
}
const onAddPersonOk = (fileList) => {
  personList.value = fileList
}
const otherOperate = () => {
  closeTab(true)
}
const okLoading = () => {
  loading.value = false
}
const handleOk = async (status) => {
  // loading.value = true
  try {
    let params = queryParams()
    if (!params.lineId || params.staffIds?.length == 0 || params.stationNos?.length == 0 || !operateProcList.value.version){
      message.error(t('other.mandatoryNull'))
      loading.value = false
      return
    }
    if (!isEmpty(operateProcList.value.processInfoList)){
      const standardSecondsValue = operateProcList.value.processInfoList.findIndex(item=>item.standardSeconds === 0)
      if (standardSecondsValue >= 0){
          message.error(t('other.standardTimeNotBe'))
          loading.value = false
          return
      }
    }
    await operateProcList.value.listFormRef.validateFields()
    params.status = status;
    await loadingDiagRef.value.open(true) 
    const res = await axios.postAction('/api/mo/mo/production-scheduling', params) 
    if (res.success) { 
      if (!isEmpty(res.data)){
        await loadingDiagRef.value.open(false)
        if (res.data.ieRoadmapProcRoadmapVO.hangerLineIdList){
          let resLine = await axios.postAction('/api/device/station/get-hangerLineId-by-station',{hangerLineIdList: res.data.ieRoadmapProcRoadmapVO.hangerLineIdList})
          // console.log(resLine)
          if (resLine.success){  lineStationList.value = resLine.data; }
        }
        await addRouteModalRef.value.open(res.data,lineStationList.value)
      }
      await loadingDiagRef.value.open(false)
    }
  loading.value = false
  } catch (err) {
    await loadingDiagRef.value.open(false)
    loading.value = false
  }
}
const closeTab = async (isSuccess) => {
  const tabList = cloneDeep(tabs.value)
  let changeTabs = tabList.filter((i) => {
    if (isSuccess) {
      return !['/makeManage/aiSchedule', route.path].includes(i.path)
    } else {
      return i.path !== route.path
    }
  })
  await store.commit('updateState', { tabs: changeTabs })
  router.replace({ path: '/makeManage/routeChart' })
}
const queryParams = () => {
  let params = {...recordInfo.value}
  params.lineId = formState.value.lineId
  params.staffIds = personList.value.map(item=>{return item.key})
  params.stationNos = stationList.value.map(item=>{return item.key})
  let list = cloneDeep(operateProcList.value.processInfoList)
  list.forEach(i=> {
    i.maxStationNo = i.maxStationNo <0 ? null : i.maxStationNo 
  })
  params.ieRoadmapProcVO = {
    detailList: list || [],
    id:operateProcList.value.version,
    name:operateProcList.value.ieRoadmapProcVO.name || '',
  }
  // console.log("🚀 🚀🚀🚀🚀🚀🚀🚀🚀🚀", params)
  return params
} 
const initMethod = async () => {
  try {
    const resStaff = await axios.postAction('/api/basic/staff/list')
    if (resStaff.success) staffList.value = resStaff.data
    const resGroup = await axios.postAction('/api/basic/staff-group/list')
    if (resGroup.success) staffGroupList.value = resGroup.data
    let resLine = await axios.postAction('/api/device/hanger-line/list')
    if (resLine.success){  lineList.value = resLine.data; } 
  }catch (err){
    console.log(err)
    closeTab()
  }
}
const getDetailInfo = async (id) => {
  try {
    const res = await axios.getAction('/api/mo/mo/get',{ id:id })
    if (res.success) {
      let { id, moNo ,styleNo, productType, quantity, createTime } = res.data
      recordInfo.value = {
        ieRoadmapProcVO:{},
        lineId:null, moId:id, moNo:moNo, styleNo:styleNo, productType:productType, quantity:quantity,userNum:'', createTime:createTime,
        staffIds:[],
        stationNos:[],
        status:Number,
      }
    } 
  } catch {
    closeTab()
  }
}
onMounted(async () => {
  loading.value = true 
  if ( isEmpty(route.query.moId) ) {
    // closeTab()
    loading.value = false
    return
  }
  await initMethod()
  await getDetailInfo(route.query.moId) 
  loading.value = false
})
</script>
